import { useEffect, useState, useMemo } from "react"
import styled from "styled-components"

interface TimeBoxProps {
    seconds: number
    onTimeUp?: () => void
}

const TimeBoxWrapper = styled.div`
    display: flex;
    gap: 12rem;
`

const TimeUnit = styled.div`
    width: 56rem;
    height: 52rem;
    background: #f2f3f5;
    border-radius: 8rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 8rem 0 8rem 0;
    .number {
        font-size: 20rem;
        font-weight: 700;
        color: #1d2129;
        line-height: 26rem;
        height: 26rem;
    }

    .label {
        font-size: 12rem;
        color: #4e5969;
        line-height: 16rem;
    }
`

function TimeBox({ seconds: initialSeconds, onTimeUp }: TimeBoxProps) {
    const [timeLeft, setTimeLeft] = useState(initialSeconds)

    useEffect(() => {
        if (timeLeft <= 0) {
            onTimeUp?.()
            return
        }

        const timer = setInterval(() => {
            setTimeLeft((prev) => {
                if (prev <= 1) {
                    clearInterval(timer)
                    onTimeUp?.()
                    return 0
                }
                return prev - 1
            })
        }, 1000)

        return () => clearInterval(timer)
    }, [timeLeft, onTimeUp])

    const { hours, minutes, remainingSeconds } = useMemo(() => {
        const hours = Math.floor(timeLeft / 3600)
        const minutes = Math.floor((timeLeft % 3600) / 60)
        const remainingSeconds = timeLeft % 60

        return {
            hours: String(hours).padStart(2, "0"),
            minutes: String(minutes).padStart(2, "0"),
            remainingSeconds: String(remainingSeconds).padStart(2, "0"),
        }
    }, [timeLeft])

    return (
        <TimeBoxWrapper>
            <TimeUnit>
                <span className="number">{hours}</span>
                <span className="label">Hour</span>
            </TimeUnit>
            <TimeUnit>
                <span className="number">{minutes}</span>
                <span className="label">Mintue</span>
            </TimeUnit>
            <TimeUnit>
                <span className="number">{remainingSeconds}</span>
                <span className="label">Second</span>
            </TimeUnit>
        </TimeBoxWrapper>
    )
}

export default TimeBox
